/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/9/26 15:54
 */
package com.gitee.mechanic.core.utils;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.util.Assert;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛工具类
 *
 * @author mechanic
 */
public class QiniuUtils {

    private static final String QINUI_SERVER = "http://qiniu.g-easy.com.cn/";
    private static final String ACCESS_KEY = "g9n2gXqQ5SQuu1YQw8R9NTdd9SY1iyxm2e15iPgT";
    private static final String SECRET_KEY = "XDWpagJhQUdcFpuR_Y9BDT9boKQCnHLqLKII9Anc";
    private static final String BUCKET = "mechanic";

    private static UploadManager UPLOAD_MANAGER;

    static {
        UPLOAD_MANAGER = new UploadManager(new Configuration(Zone.zone2()));
    }

    /**
     * 上传文件到七牛CDN
     *
     * @param file   文件
     * @param prefix 前缀
     * @return 七牛文件的url
     * @throws IOException io异常
     */
    public static String upload(File file, String prefix) throws IOException {
        Assert.notNull(file, "文件不能为空");
        Assert.notNull(prefix, "前缀不能为空");
        String key = prefix + "/" + file.getName();
        String upToken = getAuth().uploadToken(BUCKET, key);
        Response response = UPLOAD_MANAGER.put(file, key, upToken);
        return QINUI_SERVER + key;
    }

    /**
     * 上传文件到七牛CDN
     *
     * @param text     字符串
     * @param filename 转换成文件的名
     * @param prefix   前缀
     * @return 七牛文件的url
     * @throws IOException io异常
     */
    public static String upload(String text, String filename, String prefix) throws IOException {
        Assert.notNull(text, "上传的内容不能为空");
        Assert.notNull(filename, "文件名不能为空");
        Assert.notNull(prefix, "前缀不能为空");
        String key = prefix + "/" + filename;
        String upToken = getAuth().uploadToken(BUCKET, key);
        InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
        Response response = UPLOAD_MANAGER.put(is, key, upToken, null, "text/html");
        return QINUI_SERVER + key;
    }

    private static Auth getAuth() {
        return Auth.create(ACCESS_KEY, SECRET_KEY);
    }
}
